/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.execution;

import com.softwarecraftsmen.orogeny.annotations.Orogeny;
import org.jetbrains.annotations.NotNull;

import static java.lang.String.format;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static java.util.Locale.UK;

public class OrogenyProcessor
{
	private final Annotation orogenyAnnotation;

	public OrogenyProcessor(final @NotNull Annotation orogenyAnnotation)
	{
		if (!isOrogenyAnnotation(orogenyAnnotation))
		{
			throw new IllegalArgumentException(format(UK, "The annotation %1$s is not an orogeny annotation. It needs to be decorated with @Orogeny and have a String value(); method", orogenyAnnotation));
		}
		this.orogenyAnnotation = orogenyAnnotation;
	}

	@NotNull
	public String value()
	{
		try
		{
			final Method declaredMethod = orogenyAnnotation.annotationType().getDeclaredMethod("value");
			return (String) declaredMethod.invoke(orogenyAnnotation);
		}
		catch (NoSuchMethodException e)
		{
			throw new IllegalStateException("Annotations do not support inheritance, so, by convention, all Orogeny annotations are expected to have a String value() method", e);
		}
		catch (InvocationTargetException e)
		{
			throw new IllegalStateException("Should never happen", e);
		}
		catch (IllegalAccessException e)
		{
			throw new IllegalStateException("Should never happen", e);
		}
		catch (ClassCastException e)
		{
			throw new IllegalStateException("Annotations do not support inheritance, so, by convention, all Orogeny annotations are expected to have a String value() method", e);
		}
	}

	public static boolean isOrogenyAnnotation(final @NotNull Annotation annotation)
	{
		return annotation.annotationType().getAnnotation(Orogeny.class) != null;
	}
}
